﻿// MainWindow.xaml.cs
using Microsoft.Win32;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Data;
using datatool;
using System.ComponentModel;

namespace SerialPortTool
{
    static class LoggerConfig
    {
        public static string LogPath { get; } = "logs/app.log";
        public static int MaxFileSizeMB { get; } = 10;
    }

    public class CommandItem
    {
        public string Name { get; set; }
        public byte Value { get; set; }
    }

    public partial class MainWindow : Window
    {
        private static readonly object logLock = new object();

        private void AppendLogToFile(string message)
        {
            lock (logLock)
            {
                // 自动创建日志目录
                var logDir = Path.GetDirectoryName(LoggerConfig.LogPath);
                Directory.CreateDirectory(logDir);

                // 滚动检测
                if (File.Exists(LoggerConfig.LogPath) &&
                    new FileInfo(LoggerConfig.LogPath).Length > LoggerConfig.MaxFileSizeMB * 1024 * 1024)
                {
                    string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                    string newPath = Path.Combine(logDir, $"app_{timestamp}.log");
                    File.Move(LoggerConfig.LogPath, newPath);  // 直接移动旧文件
                }

                // 写入日志
                File.AppendAllText(LoggerConfig.LogPath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} | {message}{Environment.NewLine}");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
        
        public void AppendLog(string message)
        {
            Dispatcher.Invoke(() =>
            {
                txtLog.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] {message}\n");
                txtLog.ScrollToEnd();
            });

            AppendLogToFile(message);
        }

        protected override void OnClosed(EventArgs e)
        {
            asProUC.OnClosed();
            base.OnClosed(e);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                txtLog.Clear();
            });
        }
    }

}
